#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>

#define MAXLINE 4096

inline int max(int a, int b)
{
	if(a > b) return a;
	else	return b;
}

void str_cli(FILE *fp, int sockfd)
{
	int maxfdp1;
	fd_set rset;
	char sendline[MAXLINE], recvline[MAXLINE], getstdin[MAXLINE - 4];
	int n, m;

	FD_ZERO(&rset);
	while(1) {
		FD_SET(fileno(fp), &rset);
		FD_SET(sockfd, &rset);
		maxfdp1 = max(fileno(fp),sockfd) + 1;
		select(maxfdp1, &rset, NULL, NULL, NULL);

		if (FD_ISSET(sockfd, &rset)) {
			if((n = recv(sockfd, recvline, MAXLINE, 0)) == 0){
				return;
			}
			fputs(recvline, stdout);
		}

		if(FD_ISSET(fileno(fp), &rset)) {
			if((n = read(fileno(fp), getstdin, MAXLINE - 4, 0)) == 0){
				FD_CLR(fileno(fp), &rset);
				continue;
			}
			m = n + 4;
			getstdin[n] = '\0';
			memcpy(sendline, &m, 4);
			memcpy(sendline + 4, getstdin, n);
//			printf("sendline_line:%d\n", strlen(sendline))	;
//			printf("send message :%s", sendline);

			if((n = send(sockfd, sendline, m,0)) == 0)
				printf("send message error\n");
			memset(sendline, 0, MAXLINE);
		}
		//printf("n = %d\n", n);
	}
}


int main(int argc, char** argv)
{
	int    sockfd, n;
	char sendline[MAXLINE], recvline[MAXLINE];
	struct sockaddr_in    servaddr;

	if( argc != 3){
		printf("usage: ./client <ipaddress> <port>\n");
		exit(0);
	}

	if( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
		printf("create socket error: %s(errno: %d)\n", strerror(errno),errno);
		exit(0);
	}

	memset(&servaddr, 0, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(atoi(argv[2]));
	if( inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0){
		printf("inet_pton error for %s\n",argv[1]);
		exit(0);
	}

	if( connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0){
		printf("connect error: %s(errno: %d)\n",strerror(errno),errno);
		exit(0);
	}
/*
	printf("send msg to server: \n");
	while(fgets(sendline, 4096, stdin) != NULL){
		if( send(sockfd, sendline, strlen(sendline), 0) < 0){
			printf("send msg error: %s(errno: %d)\n", strerror(errno), errno);
			exit(0);
		}

		if(recv(sockfd, recvline, MAXLINE,0) == 0){
			printf("server terminated prematurely");
			exit(0);
		}
		printf("recv msg from server:");
		fputs(recvline, stdout);
	}
*/	

	printf("send msg to server: \n");
	str_cli(stdin, sockfd);

	close(sockfd);
	exit(0);
}
